/**
 * Created by 丸子 on 2018/7/1.
 */
import Vue from 'vue'
import Base64 from './base64'
import ar from "element-ui/src/locale/lang/ar";


// url中获取参数
export function getQueryString(name) {
  const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
  const r = window.location.search.substr(1).match(reg)
  if (r != null) {
    return unescape(r[2])
  }
  return null
}

// 时间转换yyyy-MM-dd hh:mm
export function formatDate(time, fmt = 'yyyy-MM-dd hh:mm') {
  const date = new Date(time)
  const o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds(),
    'q+': Math.floor((date.getMonth() + 3) / 3),
    'S': date.getMilliseconds()
  }
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  for (let k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
  }
  return fmt
}

export function injectVueContext(context) {
  Object.assign(Vue.prototype, context)
}

function getStorageItem(name = 'localStorage', key, defaultValue, encode = true) {
  if (name in window) {
    let item = window[name].getItem(key)
    if (item) {
      try {
        item = encode ? Base64.decode(item) : item
        return JSON.parse(item)
      } catch (e) {
        // console.error(e)
        return
      }
    }
    return item
  }
  return defaultValue
}

export function setStorageItem(name = 'localStorage', key, value, encode = true) {
  if (name in window) {
    let targetValue = value
    if (value) {
      const item = JSON.stringify(value)
      targetValue = encode ? Base64.encode(item) : item
    }
    window[name].setItem(key, targetValue || '')
  }
}

export const getSessionStorageItem = getStorageItem.bind(null, 'sessionStorage')

export const setSessionStorageItem = setStorageItem.bind(null, 'sessionStorage')

export const getLocalStorageItem = getStorageItem.bind(null, 'localStorage')

export const setLocalStorageItem = setStorageItem.bind(null, 'localStorage')


export function walkTree(tree, handle, parent = null, childrenKey = 'children') {
  if (tree && tree.length) {
    handle(parent, tree);
    tree.forEach((parent2) => {
      walkTree(parent2.children, handle, parent2, childrenKey);
    })
  }
}

export function waitPromise(promise, timeout = 1000) {
  return new Promise((resolve, reject) => {
    const timer = setTimeout(() => reject(new Error('超时')), timeout);
    promise.then((r)=>{
      clearTimeout(timer);
      resolve(r);
    }, (e)=>{
      clearTimeout(timer);
      reject(e);
    });
  });
}
export function getRandomArr(arr,num){
  let resultArr = []
  let arrNew = arr.slice()
  // let arrNew = Object.assign({},arr)
  for(let i =0;i<num;i++){
    resultArr.push(arrNew.splice(Math.random(arrNew.length),1)[0])
  }
  return resultArr
}

export function sleep(time) {
  return new Promise(resolve => setTimeout(resolve, time));
}

export function delaySwitch(delayTime, defaultValue = true, targetValue = false) {
  const obj = {value: defaultValue};
  setTimeout(()=>{
    obj.value = targetValue;
  }, delayTime);
  return obj;
}

export function flattenArr(arr) {
  return arr.reduce((a, b) =>{ return a.concat(b)},[] );
}